<template>
<el-row class="container">
  <el-col :span="24" class="header">
    <el-col :span="10" class="logo" :class="collapsed?'logo-collapse-width':'logo-width'">
      <img src="../assets/logo.png" style="margin-left:0px" />{{collapsed?'':sysName}}
    </el-col>
    <el-col :span="4">
      <div class="tools" @click.prevent="collapse">
        <i class="fa fa-align-justify"></i>
      </div>
    </el-col>
    <el-col :offset="2" :span="6">
      <div style="text-align:right;">
        <span id="time"></span>

      </div>
    </el-col>
    <el-col :span="8" class="userinfo">
      <!-- 我的消息 -->
      <el-dropdown trigger="click">
        <el-badge :value="noWatchTotal" class="item">
          <el-button style="font-size:19px;padding: 10px 10px" class="el-dropdown-link"><i class="el-icon-message-solid"></i></el-button>
        </el-badge>

        <el-dropdown-menu slot="dropdown" style="width:350px">

          <h3 style="text-align:center;color:#858F99" v-show="chatList.length==0">☺当前没有新消息～</h3>
          <el-dropdown-item class="clearfix" v-for="chat in chatList" :key="chat.chatTaId" v-show="chat.noWatchCount != 0" @click.native="clickHrefChat(chat)">
             <div class="block">
              <el-badge class="mark" :value="chat.noWatchCount">
                <el-avatar  :size="39" :src="'http://192.168.43.183/files/'+chat.member.memImg"></el-avatar>
              </el-badge>&nbsp;&nbsp;
              <font size='3'>{{chat.member.memName}}</font>&nbsp;
              <span style="font-size:3px">在{{chat.lastTime}}向你发送了<font color="red">{{chat.noWatchCount}}</font>条新消息</span>
            </div>
          </el-dropdown-item>

        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown trigger="hover">
        <span class="userinfo-inner">
          <img :src="'http://192.168.43.183/files/'+circleUrl">
          <font color='yellow' size='4'>{{userInfo.hmName}}</font>，欢迎你！
        </span>
        <el-dropdown-menu slot="dropdown" style="width:133px">
          <el-dropdown-item @click.native="myInfo"><i class="el-icon-user"></i>我的信息</el-dropdown-item>
          <el-dropdown-item @click.native="clickUpTou"><i class="el-icon-picture-outline-round"></i>更换头像</el-dropdown-item>
          <input id="input" type="file" @change="fileUpload()" accept=".gif,.jpg,.jpeg,.png" v-show="false">
          <el-dropdown-item @click.native="dialogVisible = true"><i class="el-icon-edit-outline"></i>修改密码</el-dropdown-item>
          <el-dropdown-item divided @click.native="logout"><i class="el-icon-switch-button"></i>退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-col>
  </el-col>
  <el-col :span="24" class="main">
    <aside :class="collapsed ? 'menu-collapsed' : 'menu-expanded'">
      <!--导航菜单-->
      <el-menu default-active="0-0" class="el-menu-vertical-demo" @open="handleopen" @close="handleclose" :collapse="collapsed" style="overflow-y: auto;">
        <el-menu-item index='0-0' @click="routerLink('/home/welcome')">
          <i class="el-icon-menu"></i>
          <span slot="title">首页</span>
        </el-menu-item>

        <el-submenu :index="item.menuId+''" v-for="item in menus" :key="item.menuId"  >
          <template slot="title">
            <i :class="item.menuIcon"></i>
            <span slot="title">{{item.menuName}}</span>
          </template>

          <el-menu-item-group>
            <el-menu-item v-for="children in item.children" :key="children.menuId" :index='children.menuId+""' @click="routerLink(''+children.menuUrl)">
              {{children.menuName}}
            </el-menu-item>
          </el-menu-item-group>
        </el-submenu>
      </el-menu>

    </aside>
    <section class="content-container" style="backgroud-color: #EBEEF5">
      <div class="grid-content bg-purple-light">
        <el-col :span="24" class="breadcrumb-container">
          <strong class="title">{{$route.name}}</strong>
          <el-breadcrumb separator="/" class="breadcrumb-inner">
            <el-breadcrumb-item v-for="item in $route.matched" :key="item.path">
              {{ item.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </el-col>
        <el-col :span="24" class="content-wrapper">
          <transition name="fade" mode="out-in">
            <router-view name="left"></router-view>
          </transition>
        </el-col>
      </div>
    </section>
  </el-col>
  <!-- 显示我的信息的地方 -->
  <el-drawer title="我的信息" :visible.sync="drawer" direction="btt" size="60%" :before-close="handleClose">
    <div>
      <el-descriptions :column="4" size="" border>
        <template slot="extra">
          <el-button type="primary" class="el-icon-edit" size="small" @click="editUserInfo">编辑</el-button>
        </template>
        <el-descriptions-item> <template slot="label">
            <i class="el-icon-user"></i>
            姓名
          </template>
          {{userInfo.hmName}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-collection"></i>
            角色
          </template>
          {{userInfo.role == null ? '' : userInfo.role.roleName}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            手机号
          </template>
          {{userInfo.hmPhone}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-time"></i>
            出生日期
          </template>
          <el-tag size="small">{{userInfo.hmBirthday}}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-connection"></i>
            性别
          </template>
          {{userInfo.hmGender}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-timer"></i>
            年龄
          </template>
          {{userInfo.hmAge}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="iconfont icon-minzu"></i>
            民族
          </template>
          {{userInfo.hmNation}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="iconfont icon-youxiang"></i>
            邮箱
          </template>
          {{userInfo.hmEmail}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="iconfont icon-wenhuachengdu"></i>
            文化程度
          </template>
          {{userInfo.hmDegree}}
        </el-descriptions-item>
        <el-descriptions-item :span="3">
          <template slot="label">
            <i class="el-icon-office-building"></i>
            联系地址
          </template>
          {{userInfo.hmAddress}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="iconfont icon-gerenjieshao"></i>
            个人介绍
          </template>
          {{userInfo.hmDesc}}
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </el-drawer>

  <!-- 修改密码对话框 -->
  <el-dialog title="修改密码页面" :visible.sync="dialogVisible" width="50%" :before-close="handleClose1">
    <el-steps :active="active" finish-status="success" simple style="margin-top: 20px">
      <el-step title="验证" ></el-step>
      <el-step title="修改密码"></el-step>
      <el-step title="完成" ></el-step>
    </el-steps>

    <div v-show="flag1" style="margin-top:23px">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="绑定手机号" label-width="100">
          <el-input v-model="userInfo.hmPhone" readonly></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :disabled="disabledBtn">{{btnContent}}</el-button>
        </el-form-item>
      </el-form>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="输入验证码" label-width="100">
          <el-input v-model="yanzhengma" style="width:206.4px"></el-input><span style="color:red">{{msg1}}</span>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="yanzhengClick">下一步</el-button>
    </div>
    <div v-show="flag2">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="密码" prop="pass" style="margin-top:23px">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass" style="margin-top:23px">
          <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item style="margin-top:23px">
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-show="flag3">
      <el-result icon="success" title="修改成功" subTitle="已成功更新密码">
        <template slot="extra">
          <el-button type="primary" size="medium" @click="returnZhu">返回主页</el-button>
        </template>
      </el-result>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose1">关 闭</el-button>
    </span>
  </el-dialog>

  <!-- 修改个人信息对话框 -->
  <el-dialog title="收货地址" :visible.sync="dialogFormVisible" :before-close="upUserInfoDialogClose">
    <el-form :model="upUserInfo">
      <el-form-item label="姓名" :label-width="formLabelWidth">
        <el-input v-model="upUserInfo.hmName" autocomplete="off" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="身份证号码" :label-width="formLabelWidth" >
        <el-input v-model="upUserInfo.hmIdentity" autocomplete="off" maxlength="18"></el-input>
      </el-form-item>
      <el-form-item label="性别" :label-width="formLabelWidth">
        <el-select v-model="upUserInfo.hmGender" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="民族" :label-width="formLabelWidth">
        <el-input v-model="upUserInfo.hmNation" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth">
        <el-input v-model="upUserInfo.hmEmail" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="文化程度" :label-width="formLabelWidth">
        <el-input v-model="upUserInfo.hmDegree" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="联系地址" :label-width="formLabelWidth">
        <el-input v-model="upUserInfo.hmAddress" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="个人介绍" :label-width="formLabelWidth">
        <el-input type="textarea" v-model="upUserInfo.hmDesc" autocomplete="off" maxlength="200" show-word-limit></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitUpUserInfo">确认修改</el-button>
    </div>
  </el-dialog>

</el-row>
</template>

<script>
export default {
  data () {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      sysName: '体检管理系统',
      collapsed: false, // 收缩菜单
      menus: [], // 菜单展示
      userInfo: {}, // 个人信息
      drawer: false, // 抽屉的显示变量
      circleUrl: '', // 图片的变量
      dialogVisible: false, // 修改密码的对话框
      active: 0, // 步骤条显示到哪一步
      flag1: true,
      flag2: false,
      flag3: false,
      yanzhengma: '',
      jishiqi: null,
      count: 120,
      disabledBtn: false,
      btnContent: '获取验证码',
      msg1: '',
      msg2: '',
      msg3: '',
      ruleForm: {
        pass: '',
        checkPass: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      formLabelWidth: '120px', // 修改个人信息表单标签宽度变量
      dialogFormVisible: false, // 修改个人信息对话框打开变量
      upUserInfo: {},
      chatList: [], // 未查看消息数组
      noWatchTotal: 0
    }
  },
  methods: {
    handleopen (key, keyPath) {
      // console.log(keyPath)
    },
    handleclose (key, keyPath) {

    },
    handleClose1 (done) {
      this.$confirm('确认退出修该密码吗？', '提示', { type: 'warning' })
        .then(_ => {
          this.active = 0
          this.yanzhengma = ''
          this.count = 120
          this.disabledBtn = false
          this.btnContent = '获取验证码'
          this.msg1 = ''
          this.msg2 = ''
          this.msg3 = ''
          this.flag1 = true
          this.flag2 = false
          this.flag3 = false
          if (this.jishiqi != null) {
            clearInterval(this.jishiqi)
          }
          this.jishiqi = null
          this.dialogVisible = false
        })
        .catch(_ => {
          this.$message('已取消退出')
        })
    },
    upUserInfoDialogClose (done) {
      this.referenceUserInfo()
      this.dialogFormVisible = false
    },
    // 自定义点击功能改变路由
    routerLink (url) {
      this.$router.push(url)
    },
    // 我的信息
    myInfo () {
      // 显示个人信息
      this.drawer = true
    },
    // 点击修改头像
    clickUpTou () {
      document.getElementById('input').click()
    },
    // 上传头像
    fileUpload () {
      var files = document.getElementById('input').files
      var params = new FormData()
      params.append('file', files[0])
      this.$axios({
        url: `/api/DHHealthManagerController/fileUploadTou?hmId=${this.userInfo.hmId}`,
        method: 'post',
        data: params,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(result => {
        if (result.data) {
          this.referenceUserInfo()
          this.$message({
            message: '修改头像成功！',
            type: 'success'
          })
        } else {
          this.$message.error('修改失败，出现未知错误，请稍后再试')
        }
      })
    },
    // 退出登录
    logout: function () {
      var _this = this
      this.$confirm('确认退出吗?', '提示', {
        type: 'warning'
      }).then(() => {
        sessionStorage.removeItem('user')
        _this.$router.push('/login')
        window.location.reload()
      }).catch(() => {
        this.$message('已取消退出')
      })
    },
    // 折叠导航栏
    collapse: function () {
      this.collapsed = !this.collapsed
    },
    // 查询菜单的方法
    showMenu () {
      // 这里将用户角色id传到后台 userRole
      let user = JSON.parse(sessionStorage.getItem('user'))
      this.circleUrl = user.hmImg
      this.$axios.post(`/api/CommonRole/byId?roleId=${user.roleId}`).then(({data}) => {
        user.role = data
        this.userInfo = user
        this.initChatList()
      })
      this.$axios.post(`/api/CommonMenu/showUserMenu/${user.roleId}`).then(({data}) => {
        // console.log(this.arraytotree(data))
        this.menus = this.arraytotree(data)
      })
      setInterval(() => {
        this.initChatList()
      }, 3000)
    },
    // 组装菜单的方法
    arraytotree (arr) {
      var top = []
      var sub = []
      var tempObj = {}
      arr.forEach(function (item) {
        if (item.parentId === 0) { // 顶级分类
          top.push(item)
        } else {
          sub.push(item) // 其他分类
        }
        item.children = [] // 默然添加children属性
        tempObj[item.menuId] = item // 用当前分类的id做key，存储在tempObj中
      })

      sub.forEach(function (item) {
        // 取父级
        var parent = tempObj[item.parentId] || {'children': []}
        // 把当前分类加入到父级的children中
        parent.children.push(item)
      })

      return top
    },
    // 关闭我的信息的方法
    handleClose (done) {
      done()
    },
    // 刷新登录的个人信息的方法
    referenceUserInfo () {
      let user = JSON.parse(sessionStorage.getItem('user'))
      this.$axios.post(`/api/DHHealthManagerController/referenceUserInfo?hmId=${user.hmId}`).then(({data}) => {
        this.userInfo = data
        this.circleUrl = data.hmImg
        this.$store.commit('saveUser', data)
        sessionStorage.setItem('user', JSON.stringify(data))
      })
    },
    // 获取验证码
    onSubmit () {
      this.disabledBtn = true
      // 获取验证码
      this.jishiqi = setInterval(() => {
        this.count--
        this.btnContent = '(' + this.count + ')重新获取'
        if (this.count === 1) {
          this.btnContent = '获取验证码'
          this.disabledBtn = false
          this.count = 120
          clearInterval(this.jishiqi)
          this.jishiqi = null
        }
      }, 1000)
      this.$axios.get(`https://cloud-music-api-lyart.vercel.app/captcha/sent?phone=${this.userInfo.hmPhone}`).then(result => {
        if (result.data.data) {
          this.$message({
            message: '验证码发送成功！',
            type: 'success'
          })
        } else {
          this.$message.error('发送失败！请稍后再试')
        }
      })
    },
    yanzhengClick () {
      if (this.yanzhengma === '') {
        this.msg1 = '请输入验证码'
      } else {
        this.$axios.get(`https://cloud-music-api-lyart.vercel.app/captcha/verify?phone=${this.userInfo.hmPhone}&captcha=${this.yanzhengma}`).then(result => {
          if (result.data.data) {
            this.flag2 = true
            this.flag1 = false
            this.active = 1
            this.$message({
              message: '验证成功！',
              type: 'success'
            })
          } else {
            this.$message.error('验证失败')
          }
        }).catch((er) => {
          this.$message.error('验证失败')
          this.msg1 = '验证码错误！'
        })
      }
    },
    // 提交修改密码
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.put(`/api/CommonHealthManager/upPasswordMethod?pass=${this.ruleForm.pass}&hmId=${this.userInfo.hmId}`).then(result => {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.active = 2
            this.flag2 = false
            this.flag3 = true
            this.referenceUserInfo()
          })
        } else {
          return false
        }
      })
    },
    // 返回主页
    returnZhu () {
      this.active = 0
      this.yanzhengma = ''
      this.count = 120
      this.disabledBtn = false
      this.btnContent = '获取验证码'
      this.msg1 = ''
      this.msg2 = ''
      this.msg3 = ''
      this.flag1 = true
      this.flag2 = false
      this.flag3 = false
      if (this.jishiqi != null) {
        clearInterval(this.jishiqi)
      }
      this.jishiqi = null
      this.dialogVisible = false
    },
    // 修改个人信息提交
    submitUpUserInfo () {
      this.$axios.put(`/api/DHHealthManagerController/upUser`, this.upUserInfo).then(result => {
        this.dialogFormVisible = false
        this.$message({
          message: '修改成功！',
          type: 'success'
        })
        this.referenceUserInfo()
      })
    },
    // 点击编辑个人信息
    editUserInfo () {
      this.upUserInfo = this.userInfo
      this.dialogFormVisible = true
    },
    // 动态时间
    clock () {
      let now = new Date()
      let year = now.getFullYear()
      let month = now.getMonth() + 1
      let day = now.getDate()

      let today = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      let week = today[now.getDay()]

      let hour = now.getHours()
      let min = now.getMinutes()
      let sec = now.getSeconds()
      if (hour < 10) {
        hour = '0' + hour
      }
      if (min < 10) {
        min = '0' + min
      }
      if (sec < 10) {
        sec = '0' + sec
      }
      let time = year + '年' + month + '月' + day + '日' + '  ' + week + ' ' + hour + ':' + min + ':' + sec
      document.getElementById('time').innerHTML = time
    },
    // 加载消息列表的方法
    initChatList () {
      this.$axios.post(`/api/DHChatTableController/homeChatTableList?hmId=${this.userInfo.hmId}`).then(({data}) => {
        this.chatList = data
        // 定义临时变量
        let temp = 0
        this.chatList.forEach(e => {
          temp += e.noWatchCount
          let time = e.messagesList[e.messagesList.length - 1].conMesTime
          let date = new Date(time)
          let month = date.getMonth() + 1
          let day = date.getDate()
          day = day < 10 ? '0' + day : day
          let hours = date.getHours()
          let minutes = date.getMinutes()
          minutes = minutes < 10 ? '0' + minutes : minutes
          time = month + '/' + day + ' ' + hours + ':' + minutes
          if (date.getFullYear() !== new Date().getFullYear()) {
            time = e.messagesList[e.messagesList.length - 1].conMesTime
          }
          e.lastTime = time
        })
        this.noWatchTotal = temp
      })
    },
    // 点击消息列表中的消息跳转
    clickHrefChat (chat) {
      this.$store.commit('addChatInfo', chat)
      // 修改查看状态
      this.$axios.put(`/api/DHChatTableController/upConsultHmWatch?chatTaId=${chat.chatTaId}`).then(result => {
        this.initChatList()
      })
      this.$router.push('/home/proscenium/consult')
    }
  },
  // 加载方法
  created () {
    // setInterval(this.clock, 1000)
    this.showMenu()
  }
}

</script>

<style scoped>
.container {
  position: absolute;
  top: 0px;
  bottom: 0px;
  width: 100%;
}
.header {
  height: 60px;
  line-height: 60px;
  /* background: #20a0ff; */
  background: rgba(43, 193, 231, 0.911);
  color:#fff;
}
.userinfo {
  text-align: right;
  padding-right: 35px;
  float: right;
}
.userinfo-inner {
cursor: pointer;
color:#fff;
}
.userinfo-inner img {
    width: 40px;
    height: 40px;
    border-radius: 20px;
    margin: 10px 0px 10px 10px;
    float: right;
  }
.logo {
height:60px;
font-size: 22px;
padding-left:20px;
padding-right:20px;
border-color: rgba(238,241,146,0.3);
border-right-width: 1px;
border-right-style: solid;
}
.logo img{
  width: 40px;
  float: left;
  margin: 10px 10px 10px 18px;
}
.txt {
  color:#fff;
}
.logo-width{
width:230px;
}
.logo-collapse-width{
width:60px
}
.tools{
padding: 0px 23px;
width:14px;
height: 60px;
line-height: 60px;
cursor: pointer;
}
.main {
display: flex;
position: absolute;
top: 60px;
bottom: 0px;
overflow: hidden;
}
.main aside {
/* flex:0 0 230px; */
width: 230px;
}
.el-menu{
  height: 100%;
}
.collapsed{
  width:60px;
}
.item{
    position: relative;
  }
.submenu{
    position:absolute;
    top:0px;
    left:60px;
    z-index:99999;
    height:auto;
    display:none;
  }
.menu-collapsed{
flex:0 0 60px;
width: 60px;
}
.menu-expanded{
flex:0 0 230px;
width: 230px;
}
.content-container {
flex:1;
overflow-y: scroll;
padding: 20px;
}
.title {
    width: 200px;
    float: left;
    color: #475669;
  }
.breadcrumb-inner {
float: right;
}
.content-wrapper {
background-color: #fff;
box-sizing: border-box;
text-align: center;
}
.my-label {
  background: #E1F3D8;
}
.my-content {
  background: #FDE2E2;
}
.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .item {
  margin-top: 10px;
  margin-right: 40px;
}
</style>
